package com.wsg.lightaccounting.Model;

import android.content.Context;
import android.widget.ImageView;

import com.wsg.lightaccounting.ClassConversion;
import com.wsg.lightaccounting.DB.DB;
import com.wsg.lightaccounting.R;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by dell-pc on 2016/11/10.
 */

public class RecordManager {
    private Context context;
    public static RecordManager recordManager;
    public static DB db;

    public static List<Expenditure> expenditures;
    public static List<Income> incomes;
    public static List<ExpenditureType> expenditureTypes;
    public static List<IncomeType> incomeTypes;
    public static List<AccountBooks> accountBookses;
    public static List<AA> aas;
    public static List<Record> records;

    private RecordManager(Context context){
        this.context = context;
        try {
            db = DB.getInstance(context);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static RecordManager getRecordManager(Context context){
        if (recordManager == null)  recordManager = new RecordManager(context);
        return recordManager;
    }
    public void addExpenditure(Expenditure expenditure){

        db.insertExpenditure(expenditure);
        expenditures.add(expenditure);
        records.add(expenditure);
        for (int i = 0; i <AccountManager.accounts.size() ; i++) {
            if (AccountManager.accounts.get(i).getId() == expenditure.getMoneytype()){
                AccountManager.accounts.get(i).setBalance(AccountManager.accounts.get(i).getBalance()-expenditure.getMoney());
                db.updateAccount(AccountManager.accounts.get(i));
                break;
            }
        }
        dataSort();
    }
    public void addIncome(Income income){
        db.insertIncome(income);
        incomes.add(income);
        records.add(income);
        for (int i = 0; i <AccountManager.accounts.size() ; i++) {
            if (AccountManager.accounts.get(i).getId() == income.getMoneytype()) {
                AccountManager.accounts.get(i).setBalance(AccountManager.accounts.get(i).getBalance() + income.getMoney());
                db.updateAccount(AccountManager.accounts.get(i));
                break;
            }
        }
        dataSort();
    }
    public  void setIcon(ImageView view,boolean isexpenditure,int id){
        if (isexpenditure) {
            String buttonID = "out_type" + (id+1) ;
            int resID = context.getResources().getIdentifier(buttonID, "mipmap", "com.wsg.lightaccounting");
            view.setBackgroundResource(resID);
        }
        else {
            String buttonID = "in_type" + (id+1) ;
            int resID = context.getResources().getIdentifier(buttonID, "mipmap", "com.wsg.lightaccounting");
            view.setBackgroundResource(resID);
        }
    }

    public static void dataSort(){
        Collections.sort(RecordManager.records, new Comparator<Record>() {
            @Override
            public int compare(Record lhs, Record rhs) {
                if (lhs.getDate().getTime() > rhs.getDate().getTime()){
                    return -1;
                }
                else if (lhs.getDate().getTime() == rhs.getDate().getTime()){
                    return 0;
                }
                else{
                    return 1;
                }
            }
        });
    }
    public synchronized void deleteRecord(Record record){
        if(record.isExpenditure()){
            Expenditure expenditure = (Expenditure) record;
            long id = expenditure.getId();
            db.deleteExpenditure(id);
            for (int i = 0; i <AccountManager.accounts.size() ; i++) {
                if (AccountManager.accounts.get(i).getId() == expenditure.getMoneytype()) {
                    AccountManager.accounts.get(i).setBalance(AccountManager.accounts.get(i).getBalance() + expenditure.getMoney());
                    db.updateAccount(AccountManager.accounts.get(i));
                    expenditures.remove(expenditure);
                    break;
                }
            }
        }
        else{
            Income income = (Income) record;
            long id = income.getId();
            db.deleteIncome(id);
            for (int i = 0; i <AccountManager.accounts.size() ; i++) {
                if (AccountManager.accounts.get(i).getId() == income.getMoneytype()) {
                    AccountManager.accounts.get(i).setBalance(AccountManager.accounts.get(i).getBalance() - income.getMoney());
                    db.updateAccount(AccountManager.accounts.get(i));
                    incomes.remove(income);
                    break;
                }
            }
        }
        records.remove(record);
    }
    public  void getAllRecord(){
        try {
            db.getAllRecord();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    public float[][] getSevenDateSum(Date date){
        float[][] sum = new float[2][7];
        Calendar rightNow = Calendar.getInstance();
        for (int i = 0; i < 7; i++) {
            rightNow.setTime(date);
            rightNow.add(Calendar.DAY_OF_YEAR,-i);
            Date dt1=rightNow.getTime();
            sum[0][i] = getDateExpenditureSum(ClassConversion.dateToString(dt1,"yyyy-MM-dd"));
            sum[1][i] = getDateIncomeSum(ClassConversion.dateToString(dt1,"yyyy-MM-dd"));
        }
        return sum;
    }


    public float getDateExpenditureSum(String date){
        float sum = 0f;
        long start=0L,end=0L;
        String dateStart = date + " 00:00:00";
        String dateEnd = date + " 23:59:59";
        try {
             start = ClassConversion.stringToLong(dateStart,"yyyy-MM-dd HH:mm:ss");
             end = ClassConversion.stringToLong(dateEnd,"yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        for (int i = 0; i <records.size() ; i++) {
            if (records.get(i).getDate().getTime()>= start && records.get(i).getDate().getTime() <= end){
                if (records.get(i).expenditure) {
                    sum = sum + records.get(i).getMoney();
                }
            }
        }
        return sum;
    }

    public float getDateIncomeSum(String date){
        float sum = 0f;
        long start=0L,end=0L;
        String dateStart = date + " 00:00:00";
        String dateEnd = date + " 23:59:59";
        try {
            start = ClassConversion.stringToLong(dateStart,"yyyy-MM-dd HH:mm:ss");
            end = ClassConversion.stringToLong(dateEnd,"yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        for (int i = 0; i <records.size() ; i++) {
            if (records.get(i).getDate().getTime()>= start && records.get(i).getDate().getTime() <= end){
                if (!records.get(i).expenditure) {
                    sum = sum + records.get(i).getMoney();
                }
            }
        }
        return sum;
    }

    public List<DateSum> getDataSums(){
        List<DateSum> list = new LinkedList<>();
        float[][] sum = new float[2][7];
        Calendar rightNow = Calendar.getInstance();
        java.util.Date date = new java.sql.Date(System.currentTimeMillis());
        for (int i = 0; i < 7; i++) {
            rightNow.setTime(date);
            rightNow.add(Calendar.DAY_OF_YEAR,-i);
            java.util.Date dt1=rightNow.getTime();
            sum[0][i] = getDateExpenditureSum(ClassConversion.dateToString(dt1,"yyyy-MM-dd"));
            sum[1][i] = getDateIncomeSum(ClassConversion.dateToString(dt1,"yyyy-MM-dd"));
            list.add(new DateSum(dt1,sum[1][i]-sum[0][i]));
        }
        return list;
    }


    public List<TypeSum> getExpenditrueTypeSum(){
        List<TypeSum> floats = new LinkedList<>();
        for (int i = 0; i < expenditureTypes.size(); i++) {
            float sum = getExpenditureTypeSum(expenditureTypes.get(i).getId());
            if (sum!=0f){
                floats.add(new TypeSum(sum,expenditureTypes.get(i).getName()));
            }
        }
        return  floats;
    }

    public List<TypeSum> getIncomeTypeSum(){
        List<TypeSum> floats = new LinkedList<>();
        for (int i = 0; i < incomeTypes.size(); i++) {
            float sum = getIncomeTypeSum(incomeTypes.get(i).getId());
            if (sum!=0f){
                floats.add(new TypeSum(sum,incomeTypes.get(i).getName()));
            }
        }
        return  floats;
    }

    public float getExpenditureTypeSum(long id){
        float sum = 0f;
        for (int j = 0; j < expenditures.size(); j++) {
            if (expenditures.get(j).getConsumptiontype() == id){
                sum = sum + expenditures.get(j).getMoney();
            }
        }
        return sum;
    }

    public float getIncomeTypeSum(long id){
        float sum = 0f;
        for (int j = 0; j < incomes.size(); j++) {
            if (incomes.get(j).getIncometype() == id){
                sum = sum + incomes.get(j).getMoney();
            }
        }
        return sum;
    }
}
